/*
 * Project: Set Sample
 * Copyright (C) 2013 alf.labs gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.alflabs.setsample.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.*;
import android.view.View;
import android.widget.TextView;
import com.alflabs.annotations.NonNull;
import com.alflabs.setsample.R;
import com.alflabs.setsample.stats.SetResult;

public class SetCompletedDialog extends DialogFragment {

    @SuppressWarnings("unused")
    private static final String TAG = SetCompletedDialog.class.getSimpleName();

    public interface ICompletedDialogCallback {
        public void onCompletedDialogCancel();
        public void onCompletedDialogNewBoard();
    }

    static void showDialog(FragmentActivity activity,
                           SetResult setResult) {
        // based on http://developer.android.com/reference/android/app/DialogFragment.html
        FragmentManager fm = activity.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prev = fm.findFragmentByTag("dialog");                                             //NLS
        if (prev != null) ft.remove(prev);
        ft.addToBackStack(null);
        // Note: DialogFragment *must* have an empty constructor to be restored properly by
        // the system on config changes. Use setArguments(bundle) to pass data and access
        // parent activity via an interface callback.
        SetCompletedDialog df = new SetCompletedDialog();
        df.setArguments(toBundle(setResult));
        df.show(ft, "dialog");                                                                      //NLS
    }

    // -----------

    private static Bundle toBundle(SetResult setResult) {
        Bundle b = new Bundle();
        b.putInt("getLevel", setResult.getLevel());                                               //NLS
        b.putBoolean("isNewFastest", setResult.isNewFastest());                                   //NLS
        b.putLong("getBoardTimeMs", setResult.getBoardTimeMs());                                  //NLS
        b.putLong("getFastestTimeMs", setResult.getFastestTimeMs());                              //NLS
        b.putLong("getAvgTimeMs", setResult.getAvgTimeMs());                                      //NLS
        return b;
    }

    private static SetResult fromBundle(Bundle b) {
        return new SetResult(
                b.getInt("getLevel"),                                                               //NLS
                b.getBoolean("isNewFastest"),                                                       //NLS
                b.getLong("getBoardTimeMs"),                                                        //NLS
                b.getLong("getFastestTimeMs"),                                                      //NLS
                b.getLong("getAvgTimeMs"));                                                         //NLS
    }

    @Override
    public Dialog onCreateDialog(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        SetResult result = fromBundle(getArguments());
        AlertDialog.Builder b = new AlertDialog.Builder(getActivity());

        TextView f;
        View root = getActivity().getLayoutInflater().inflate(R.layout.set_completed_dialog, null);
        assert root != null;
        setText(root, R.id.textNumSolutions,    Integer.toString(result.getLevel()));
        setText(root, R.id.textBoardTime,       SetBoardFragment.formatTime(sb, result.getBoardTimeMs(), false));
        setText(root, R.id.textAvgTime,         SetBoardFragment.formatTime(sb, result.getAvgTimeMs(), false));
        setText(root, R.id.textTimePerSolution, SetBoardFragment.formatTime(sb, result.getBoardTimeMs() / result.getLevel(), false));
        setText(root, R.id.textFastestTime,     SetBoardFragment.formatTime(sb, result.getFastestTimeMs(), false));

        if (result.isNewFastest()) {
            View v = root.findViewById(R.id.isFastestTime);
            if (v != null) v.setVisibility(View.VISIBLE);
        }

        b.setView(root);

        b.setNegativeButton("Main Menu", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                FragmentActivity a = getActivity();
                if (a instanceof ICompletedDialogCallback) {
                    ((ICompletedDialogCallback) a).onCompletedDialogCancel();
                }
            }
       });

        b.setPositiveButton("New Board", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                FragmentActivity a = getActivity();
                if (a instanceof ICompletedDialogCallback) {
                    ((ICompletedDialogCallback) a).onCompletedDialogNewBoard();
                }
            }
        });

        return b.create();
    }

    private void setText(@NonNull View root, int textId, @NonNull String value) {
        View v = root.findViewById(textId);
        if (v instanceof TextView) {
            ((TextView) v).setText(value);
        }
    }
}
